package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.exception.NoStockException;
import com.atguigu.gulimall.ware.feign.OrderFeiginService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.LockStockResult;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang.enums.Enum;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;
    @Resource
    WareOrderTaskDetailService wareOrderTaskDetailService;
    @Resource
    WareOrderTaskService wareOrderTaskService;
    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    OrderFeiginService orderFeiginService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entities == null || entities.size() == 0){
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                if(info.getCode() == 0){
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }


            wareSkuDao.insert(skuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo stockVo = new SkuHasStockVo();
            Integer count = baseMapper.getSkuStock(skuId);
            stockVo.setSkuId(skuId);
            stockVo.setHasStock(count == null ? false : count > 0);
            return stockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某个订单锁库存
     * @param vo
     *
     * 库存解锁场景
     * 1、下单成功，用户手动取消，订单过期被系统自动取消。都需要解锁库存
     * 2、下订单成功，库存锁定，接下来的业务调用异常，导致订单回滚。
     *    之前锁定的库存需要解锁
     *
     * @return
     */
    @Transactional
    @Override
    public Boolean orderStockLock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单详情。
         * 溯源使用
         */
        WareOrderTaskEntity entity = new WareOrderTaskEntity();
        entity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(entity);

        //1、按照下单收货地址找到，就近的仓库，锁定仓库
        List<OrderItemVo> items = vo.getItems();

        //2、查找每个商品在哪些仓库有库存
        List<SkuWareHasStock> collect = items.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        //3、对每一个商品进行锁库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStock = false; //默认库存没有被锁定
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if(wareIds == null || wareIds.size() == 0){
                //没有任何库存则抛出异常
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                //更新库存，如果成功返回1，失败返回0
                Integer count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if(count == 1){
                    // 当前商品有库存锁住了
                    skuStock = true;
                    // TODO 告诉mq库存锁定成功，并在数据库保存
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
                    detailEntity.setWareId(wareId);
                    detailEntity.setLockStatus(1);
                    detailEntity.setSkuId(skuId);
                    detailEntity.setTaskId(entity.getId());
                    detailEntity.setSkuNum(hasStock.getNum());
                    wareOrderTaskDetailService.save(detailEntity);

                    //锁定成功发送到mq延时队列上
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setTaskId(entity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity, detailTo);
                    stockLockedTo.setDetail(detailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked",stockLockedTo );
                    break;
                }else {
                    //当前商品库存不足，没有锁住
                }
            }
            if(!skuStock){ //如果当前商品没有锁住
                throw new NoStockException(skuId);
            }
        }

        //锁成功
        return true;
    }

    @Override
    public void unLockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        /**
         * 解锁：
         *   1、查询数据库关于这个订单的锁定库存信息
         *   有：考虑是否解锁
         *      需要解锁：订单状态
         *         1、没有这个订单。必须解锁
         *         2、有这个订单。看订单状态
         *            订单状态：已取消，解锁库存
         *                    没取消，不能解锁
         *   没有：不需要解锁
         */
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detail.getId());
        if(byId != null){
            //解锁
            Long taskId = to.getTaskId();
            WareOrderTaskEntity byId1 = wareOrderTaskService.getById(taskId);
            R orderStatus = orderFeiginService.getOrderStatus(byId1.getOrderSn());
            if(orderStatus.getCode() == 0){
                //订单返回成功
                OrderVo data = orderStatus.getData(new TypeReference<OrderVo>() {
                });
                if(data == null || data.getStatus() == 4){
                    //订单不存在或者订单已取消都需要解锁
                    if(byId.getLockStatus() == 1){
                        //必须是未锁定的状态才能解锁
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), byId.getId());
                    }
                }
            }else {
                //请求失败后把消息重新放回队列中
                throw new RuntimeException("请求订单失败");
            }
        }else{
            //无需解锁
        }
    }

    @Transactional
    @Override
    public void unLockStock(OrderTo to) {
        WareOrderTaskEntity order_sn = wareOrderTaskService.getOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", to.getOrderSn()));
        Long taskId = order_sn.getId();
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", taskId).eq("lock_status", 1));
        if(list != null && list.size()>0){
            for (WareOrderTaskDetailEntity detailEntity : list) {
                unLockStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum(), detailEntity.getId());
            }
        }
    }


    private void unLockStock(Long skuId, Long wareId, Integer num, Long detailId){
        wareSkuDao.unLockStock(skuId, wareId, num);
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(detailId);
        detailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(detailEntity);
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }
}